import json
from fastapi import APIRouter
from conf.settings import *
from cmg_base import dispatch_service_discovery
router = APIRouter()


discovery = dispatch_service_discovery(YAML_CONFIG.get_cmg_url())

@router.get("/list")
async def list_services():
    try:
        res = {}
        services = discovery.get_services()
        for service in services:
            count = discovery.get_instance_count(service)
            res[service] = count
    except Exception as exc:
        return {
            "code": 1,
            "data": "",
            "err_msg": str(exc)
        }
    return {
        "code": 0,
        "data": res,
        "err_msg": "" 
    }
    
@router.get("/list_detail")
async def list_services():
    try:
        res = {}
        services = discovery.get_services()
        for service in services:
            ss = discovery.get_instances(service)
            res[service] = [item.to_dict() for item in ss]
    except Exception as exc:
        return {
            "code": 1,
            "data": "",
            "err_msg": str(exc)
        }
    return {
        "code": 0,
        "data": res,
        "err_msg": "" 
    }